/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ca;

import java.io.FileInputStream;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import model.CA_Service;
import model.FilePathDAO;
import model.KeyIO;
import sun.misc.BASE64Decoder;
import sun.security.x509.X509CertImpl;

/**
 *
 * @author TuanNguyen
 */
@WebService()
public class AuthenService {

    /**
     * Web service operation
     */
    @WebMethod(operationName = "authenticate")
    public String authenticate(@WebParam(name = "certEncoded") String certEncoded) {
        try {

            // tái tạo cert
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] certBytes = decoder.decodeBuffer(certEncoded);
            X509CertImpl certImpl = new X509CertImpl(certBytes);

            //chứng thực
            boolean verify = false, validate = false, isRevoke = true;
            String pubFilePath = FilePathDAO.getFilePath("pub");
            String priFilePath = FilePathDAO.getFilePath("pri");
            String crlFilePath = FilePathDAO.getFilePath("crl");
            verify = CA_Service.verifyCert(certImpl, KeyIO.getPublicKey(new FileInputStream(pubFilePath)));
            validate = CA_Service.validateCert(certImpl);

            if (crlFilePath != null) {
                isRevoke = CA_Service.isRevoke(certImpl, new FileInputStream(crlFilePath), KeyIO.getPrivateKey(new FileInputStream(priFilePath)));
            } else {
                isRevoke = false;
            }

            if (verify == true && validate == true && isRevoke == false) {
                return "valid";
            }
            System.out.println(verify);
            System.out.println(validate);
            System.out.println(isRevoke);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "invalid";
    }
}
